<template>
  <div class="meal-management">
    <div class="page-header">
      <h2>长者餐饮记录</h2>
      <p class="page-description">用心记录每一餐，守护长者健康饮食</p>
    </div>

    <div class="filter-section">
      <el-row :gutter="20">
        <!-- 管理员 + 护工：显示老人选择 -->
        <el-col :span="6" v-if="role === 'admin' || role === 'caregiver'">
          <el-select v-model="selectedElder" placeholder="选择长者" clearable @change="load" class="filter-item">
            <el-option v-for="e in elders" :key="e.elderId" :label="e.name" :value="e.elderId" />
          </el-select>
        </el-col>

        <!-- 所有人：显示日期选择 -->
        <el-col :span="6">
          <el-date-picker 
            v-model="selectedDate" 
            placeholder="选择日期" 
            clearable 
            @change="load" 
            class="filter-item"
            type="date"
          />
        </el-col>

        <!-- 状态筛选 -->
        <el-col :span="6">
          <el-select v-model="selectedStatus" placeholder="记录状态" clearable @change="load" class="filter-item">
            <el-option label="正常记录" value="ACTIVE" />
            <el-option label="编辑失误" value="EDIT_ERROR" />
            <el-option label="记录失效" value="INVALID" />
          </el-select>
        </el-col>

        <el-col :span="6">
          <el-button type="primary" @click="load" class="filter-item">查询记录</el-button>
        </el-col>

        <el-col :span="6" style="text-align: right;">
          <el-button type="success" @click="openAdd()" class="add-button">记录今日餐饮</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table :data="tableData" row-key="recordId" class="meal-table">
      <el-table-column prop="mealDate" label="用餐日期" width="120" />
      <el-table-column prop="mealType" label="餐次类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getMealTypeTag(row.mealType)">
            {{ row.mealType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="calories" label="热量(kcal)" width="100" />
      <el-table-column prop="remark" label="餐饮内容" min-width="200" />
      <el-table-column prop="statusDescription" label="记录状态" width="120">
        <template #default="{ row }">
          <el-tag 
            :type="getStatusType(row.status)" 
            effect="light"
            class="status-tag"
          >
            {{ row.statusDescription || getDefaultStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">修改记录</el-button>
          <el-button 
            v-if="role !== 'caregiver'" 
            type="danger" 
            size="small" 
            @click="del(row.recordId)"
          >
            删除
          </el-button>
          <el-button 
            v-if="role === 'caregiver'" 
            type="warning" 
            size="small" 
            @click="markAsInvalid(row.recordId)"
          >
            标记失效
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="show" :title="isAdd ? '新增记录' : '编辑记录'">
      <el-form :model="form" label-width="100px">
        <el-form-item label="老人ID"><el-input v-model="form.elderId" /></el-form-item>
        <el-form-item label="日期"><el-input v-model="form.mealDate" placeholder="yyyy-MM-dd" /></el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.mealType">
            <el-option label="早餐" value="早餐" />
            <el-option label="午餐" value="午餐" />
            <el-option label="晚餐" value="晚餐" />
          </el-select>
        </el-form-item>
        <el-form-item label="热量"><el-input v-model="form.calories" /></el-form-item>
        <el-form-item label="备注"><el-input v-model="form.remark" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getMealList, addMeal, updateMeal, deleteMeal, getElderList, getEldersByCaregiver } from '@/api/meal'
import axios from '@/api/axios'

const tableData = ref([])
const elders = ref([])
const selectedElder = ref(null)
const selectedDate = ref(null)
const selectedStatus = ref(null)
const show = ref(false)
const isAdd = ref(true)
const form = ref({})

const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
const role = userInfo.role

const load = async () => {
  const params = {}
  if (selectedElder.value) params.elderId = selectedElder.value
  if (selectedDate.value) {
    const d = selectedDate.value
    params.mealDate = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
  }
  if (selectedStatus.value) params.status = selectedStatus.value
  const res = await getMealList(params)
  tableData.value = res.data
}

// 获取餐次类型标签样式
const getMealTypeTag = (mealType) => {
  const typeMap = {
    '早餐': 'primary',
    '午餐': 'success', 
    '晚餐': 'warning'
  }
  return typeMap[mealType] || 'info'
}

// 获取状态标签样式
const getStatusType = (status) => {
  const statusMap = {
    'ACTIVE': 'success',
    'EDIT_ERROR': 'warning',
    'INVALID': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取默认状态描述
const getDefaultStatus = (status) => {
  const statusMap = {
    'ACTIVE': '正常记录',
    'EDIT_ERROR': '编辑失误',
    'INVALID': '记录失效'
  }
  return statusMap[status] || '未知状态'
}

// 标记记录为失效
const markAsInvalid = async (recordId) => {
  try {
    await axios.put(`/caregiver/meal/${recordId}/status`, { status: 'INVALID' })
    ElMessage.success('记录已标记为失效')
    load()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const openAdd = () => {
  form.value = {}
  isAdd.value = true
  show.value = true
}

const openEdit = (row) => {
  form.value = { ...row }
  isAdd.value = false
  show.value = true
}

const submit = async () => {
  isAdd.value ? await addMeal(form.value) : await updateMeal(form.value.recordId, form.value)
  show.value = false
  load()
}

const del = async (id) => {
  await deleteMeal(id)
  load()
}

onMounted(async () => {
  if (role === 'caregiver') {
    elders.value = (await getEldersByCaregiver(userInfo.caregiverId)).data
    if (elders.value.length === 1) {
      selectedElder.value = elders.value[0].elderId
    }
  } else if (role === 'family') {
    // ✅ 家属自动查 elderId
    const res = await axios.get('/caregiver/meal/elderId')
    selectedElder.value = res.data
  } else if (role === 'admin') {
    //elders.value = (await getElderList()).data
    // 1. 用已有接口拿全部餐饮记录
    const { data: meals } = await axios.get('/caregiver/meal/all')
    // 2. 提取不重复老人
    const map = new Map()
    meals.forEach(m => map.set(m.elderId, m.elderName))
    // 3. 转成下拉需要的格式
    elders.value = Array.from(map.entries()).map(([id, name]) => ({ elderId: id, name }))
  }

  await load()
})

</script>

<style scoped>
.meal-management {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  animation: fadeInDown 0.8s ease-out;
}

.page-header h2 {
  color: #2c3e50;
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: 600;
}

.page-description {
  color: #7f8c8d;
  font-size: 16px;
  margin: 0;
  font-style: italic;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  animation: slideInUp 0.6s ease-out;
}

.filter-item {
  width: 100%;
}

.add-button {
  background: linear-gradient(45deg, #27ae60, #2ecc71);
  border: none;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.add-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(46, 204, 113, 0.3);
}

.meal-table {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  animation: fadeIn 0.8s ease-out;
}

.status-tag {
  font-weight: 500;
  border-radius: 12px;
  padding: 4px 12px;
}

:deep(.el-table th) {
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
  font-weight: 600;
}

:deep(.el-table tr:hover) {
  background-color: #ecf0f1;
  transition: background-color 0.3s ease;
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
